package com.yrc.controller;

import com.yrc.enums.OrderStatusEnum;
import com.yrc.enums.PayMethod;
import com.yrc.pojo.OrderStatus;
import com.yrc.pojo.bo.ShopcartBO;
import com.yrc.pojo.bo.SubmitOrderBO;
import com.yrc.pojo.vo.MerchantOrdersVO;
import com.yrc.pojo.vo.OrderVO;
import com.yrc.service.OrderService;
import com.yrc.utils.CookieUtils;
import com.yrc.utils.JsonUtils;
import com.yrc.utils.R;
import com.yrc.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: Yrc
 * @create: 2020/11/18 22:02
 */
@Api(value = "订单相关",tags = "订单相关的api接口")
@RestController
@RequestMapping("orders")
public class OrdersController extends BaseController{

    @Autowired
    private OrderService orderService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "用户下单",notes = "用户下单",httpMethod = "POST")
    @PostMapping("/create")
    public R create(
            @RequestBody SubmitOrderBO submitOrderBO,
            HttpServletRequest request,
            HttpServletResponse response) {

        if (!submitOrderBO.getPayMethod().equals(PayMethod.WEIXIN.type)
        && !submitOrderBO.getPayMethod().equals(PayMethod.ALIPAY.type)) {
            return R.errorMsg("支付方式不支持");
        }

//        System.out.println(submitOrderBO.toString());

        String shopcartJson = redisOperator.get(FOODIE_SHOPCART + ":" + submitOrderBO.getUserId());
        if (StringUtils.isBlank(shopcartJson)) {
            return R.errorMsg("购物数据不正确");
        }

        List<ShopcartBO> shopcartList = JsonUtils.jsonToList(shopcartJson, ShopcartBO.class);

        //1.创建订单
        OrderVO order = orderService.createOrder(shopcartList,submitOrderBO);
        String orderId = order.getOrderId();
        //2.创建订单以后，移除购物车已结算（已提交）的商品
        /**
         * 1001
         * 2002 ->用户购买
         * 3003 ->用户购买
         * 4004
         */
        //清理覆盖现有的redis汇总的购物数据
        shopcartList.removeAll(order.getToBeRemovedShopcatdList());
        redisOperator.set(FOODIE_SHOPCART + ":" + submitOrderBO.getUserId(), JsonUtils.objectToJson(shopcartList));
        //整合redis之后，完善购物车中的已结算商品清除，并且同步到前端的cookie
        CookieUtils.setCookie(request, response, FOODIE_SHOPCART,JsonUtils.objectToJson(shopcartList), true);

        //3.向支付中心发送当前订单，用于保存支付中心的订单数据
        MerchantOrdersVO merchantOrdersVO = order.getMerchantOrdersVO();
        merchantOrdersVO.setReturnUrl(payReturnUrl);

        //为了方便测试购买，所以所有的支付金额都统一改为1分钱
        merchantOrdersVO.setAmount(1);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId", "imooc");
        headers.add("password", "imooc");

        HttpEntity<MerchantOrdersVO> entity = new HttpEntity<>(merchantOrdersVO, headers);

        ResponseEntity<R> rResponseEntity = restTemplate.postForEntity(paymentUrl, entity, R.class);

        R paymentResult = rResponseEntity.getBody();
        if (paymentResult.getStatus() != 200) {
            return R.errorMsg("支付中心订单创建失败，请联系管理员");
        }
        return R.ok(orderId);
    }

    @PostMapping("notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);
        return HttpStatus.OK.value();
    }

    @PostMapping("getPaidOrderInfo")
    public R getPaidOrderInfo(String orderId) {
        OrderStatus orderStatus = orderService.queryOrderStatusInfo(orderId);
        return R.ok(orderStatus);
    }

}
